'''
@Description: In User Settings Edit
@Author: your name
@Date: 2019-09-05 15:32:42
@LastEditTime: 2019-09-07 10:11:51
@LastEditors: Please set LastEditors
'''


from ...pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F,as_date
from ...service.mongo_bill_service import MongoBillFilter
from ..buss_pub.personnel_organizational import UserType
from ...service.common import GetInformationByIdCard
from enum import Enum
import datetime
from server.pao_python.pao.service.security.security_utility import SecurityConstant,get_current_account_id

class OrgType(Enum):
    '''机构类型'''
    # 福利院
    WelfarePersion = '1'
    Happiness = '2'
    Peovider = '3'

class ShowDisplayService(MongoService):

    bus_area = '南海'  # 业务区域为南海
    business_area_collection = 'PT_Business_Area'  # 业务区划表名
    current_year = 2019  # 当前年份

    '''大屏服务'''
    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd,inital_password,session):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.inital_password = inital_password
        self.session = session

    # def __org_area(self):
    #     '''找到某业务区域内的所有user'''
    #     _filter = MongoBillFilter()
    #     _filter.match(C('bus_area_config.name') == self.bus_area)\
    #            .inner_join('PT_Administration_Division', 'admin_id', 'parent_id', 'upper_admin_info')\
    #            .graph_lookup('PT_Administration_Division', '$upper_admin_info.id', 'id', 'parent_id', 'all_admin')\
    #            .project({'admin_id': '$all_admin.id'})\
    #            .unwind('admin_id')\
    #            .inner_join_bill('PT_User', 'admin_id', 'admin_area_id', 'user_info')    
    #     return _filter


    
    ####################### 公共部分 ##############################
    def set_session_area(self):
        '''设置session的区域id'''
        account_id=get_current_account_id(self.session)
        _filter=MongoBillFilter()
        _filter.match_bill(C('account_id')==account_id)\
               .lookup_bill('PT_Administration_Division','admin_area_id','id','div_info')\
               .graph_lookup('PT_Administration_Division','$div_info.parent_id','parent_id','id','all_admin')\
               .unwind('all_admin')\
               .inner_join_bill('PT_Business_Area','all_admin.id','admin_id','area_info')
        res=self.query(_filter,'PT_User')
        self.session[SecurityConstant.area] = res[0]['area_info']['id']
        return res[0]['area_info']['id']

    def get_current_user_area_id(self):
        '''通过session获取当前登录用户的区域id'''
        if SecurityConstant.area in list(self.session.keys()):
            return self.session[SecurityConstant.area]
        else:
            res=self.set_session_area()
            return res

    def ___create_list(self, obj_list):
        '''将数据转成列表
        eg : obj_list = [{'y':a},{'y':b},{'y':c}] >> [a,b,c]
        '''
        new_list = []
        if obj_list:
            for obj in obj_list:
                tep = list(obj.values())
                if tep:
                    new_list.append(tep[0])
        return new_list

    def __org_area(self):
        '''找到某业务区域内的所有user信息'''
        division_id=self.get_current_user_area_id()
        _filter = MongoBillFilter()
        _filter.match(C('id') == division_id)\
               .inner_join('PT_Administration_Division', 'admin_id', 'id', 'admin_info')\
               .graph_lookup('PT_Administration_Division', '$admin_info.parent_id', 'id', 'parent_id', 'all_admin')\
               .project({'admin_id': '$all_admin.id'})\
               .unwind('admin_id')\
               .inner_join_bill('PT_User', 'admin_id', 'admin_area_id', 'user_info')
        return _filter

    def ___org_area_organization(self,_type):
        _filter = self.__org_area()
        _filter.match(C('user_info.organization_info.personnel_category') == _type)
        return _filter
        
    def __elder_group_by_age(self, _filter):
        _filter.add_fields({'age': ((F('year')-self.current_year)*(-1)).f})\
               .add_fields({'age_range': self.ao.switch([
                    self.ao.case(((F('age') >= 60) & (F('age') < 70)),'60-69'),
                    self.ao.case(((F('age') >= 70) & (F('age') < 80)),'70-79'),
                    self.ao.case(((F('age') >= 80) & (F('age') < 90)),'80-89'),
                    self.ao.case(((F('age') >= 90) & (F('age') < 100)),'90-99'),
                    self.ao.case(((F('age') >= 100)),'100岁以上'),], '60岁以下')})
        return _filter

    # def __eld_area_basic(self):
    #     '''本行政区划内的所有长者信息'''
    #     _filter = self.__org_area()
    #     _filter.match(C('user_info.personnel_type') == UserType.Personnel)\
    #            .add_fields({'birth_year':self.ao.year('$user_info.birth_date')})\
    #            .add_fields({'age':((F('birth_year')-self.current_year)*(-1)).f})\
    #            .match(C('age')>60)
    #     return _filter
    
    # def __get_age_range(self):
    #     switch = self.ao.switch(
    #         [
    #             self.ao.case(((F('age') >= 60) & (F('age') < 70)),'60-69'),
    #             self.ao.case(((F('age') >= 70) & (F('age') < 80)),'70-79'),
    #             self.ao.case(((F('age') >= 80) & (F('age') < 90)),'80-89'),
    #             self.ao.case(((F('age') >= 90) & (F('age') < 100)),'90-99'),
    #             self.ao.case(((F('age') >= 100)),'100岁以上'),
    #              ], '60岁以下')
    #     return switch

    def _group_by_date(self, _filter,col_name,date_unit):
        '''按date进行分组统计时，对日期进行处理，处理后数据存为新的一列
        Args :
            col_name:待处理的日期列名
            date_unit：分组的日期粒度，三个值可选：日，周，月 [暂时仅支持日和月]
        '''
        if date_unit == '日':
            _filter.add_fields({'new_date': self.ao.date_to_string(col_name,'%Y-%m-%d')})
        elif date_unit == '月':
            _filter.add_fields({'new_date': self.ao.date_to_string(col_name,'%Y-%m')})
        return _filter
    
    def __com_stat_service_record(self):
        '''行政区划下幸福院的服务记录数据'''
        _filter = self.___org_area_organization('幸福院')
        _filter.inner_join_bill('PT_Service_Order','user_info.id','service_provider_id','service_order')\
            .inner_join_bill('PT_Service_Record','service_order.id','order_id','service_record')
        return _filter
    
    def ___com_stat_service(self):
        '''行政区划下幸福院的服务数据''' 
        _filter = self.__com_stat_service_record()
        _filter.inner_join_bill('PT_Service_Product','service_record.service_product_id','id','service_product')\
            .inner_join_bill('PT_Service_Item','service_product.service_item_id','id','service_item')\
            .inner_join_bill('PT_Service_Type','service_item.item_type','id','service_type')
        return _filter
    
    def ___com_detail_org(self,condition,_type='幸福院'):
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == values['id'])& (C('personnel_type') == UserType.Organizational) & (C('organization_info.personnel_category') == _type))
        return _filter
    
    def ___get_elder(self):
        '''获取行政区域内的类型为长者'''
        _filter = self.__org_area()
        _filter.match((C('user_info.personnel_type') == UserType.Personnel))
        return _filter
    
    def ___org_area_all_organization(self):
        '''获取指定业务区域内的所有组织机构'''
        _filter = self.__org_area()
        _filter.match(C('user_info.personnel_type') == UserType.Organizational)
            #    .match(C('user_info.organization_info.personnel_category') == '服务商')
        return _filter
    
    def __sep_stat_service_person(self):
        '''所有组织机构的工作人员信息'''
        _filter = self.___org_area_all_organization()
        _filter.inner_join_bill('PT_User_Relationship', 'user_info.id', 'main_relation_people', 'relation_info')\
               .inner_join_bill('PT_User_Relationship_Type', 'relation_info.relationship_type_id', 'id', 'relation_type_info')\
               .match(C('relation_type_info.name') == '雇佣')\
               .inner_join_bill('PT_User', 'relation_info.subordinate_relation_people', 'id', 'servicer_info')
        return _filter
    
    def ___current_user(self,condition):
        '''指定用户'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill(C('id')==values['id'])
        return _filter
    
    def ___list_transform(self,res):
        '''将提取list类型的数据
        eg: {x:['a']} >> {x:a}
        '''
        if res:
            for result in res:
                for key,value in result.items():
                    if type(value) == list:
                        if len(value) == 1:
                            result[key] = value[0]
                        elif len(value) == 0:
                            result[key] = ''
        return res
        # def __com_stat_service_record(self):
        # '''行政区划下幸福院的服务记录数据'''
        # _filter = self.___org_area_organization('幸福院')
        # _filter.inner_join_bill('PT_Service_Record','user_info.id','servicer_id','service_record')\
        #     .inner_join_bill('PT_Service_Order','service_record.id','service_provider_id','service_order')
        # print(_filter.filter_objects)
        # return _filter
    def __eld_area_basic(self):
        '''本行政区划内的60岁以上生存长者信息'''
        _filter = self.__org_area()
        _filter.match((C('user_info.personnel_type') == UserType.Personnel)
                     & (C('user_info.personnel_info.dead')==0)
                     & (C('user_info.personnel_info.personnel_category') == '长者'))\
               .add_fields({'year': self.ao.year('$user_info.personnel_info.date_birth')})\
               .add_fields({'age': ((F('year')-self.current_year)*(-1)).f})\
               .match(C('age') > 60)
        return _filter
    
    # def __servicer_area_basic(self):
    #     '''本行政区划内的服务人员信息'''
    #     _filter = self.__org_area()
    #     _filter.match((C('user_info.personnel_type') == UserType.Personnel)
    #                  & (C('user_info.personnel_info.personnel_category') == '服务人员'))
    #     return _filter
    
    def __org_stat_elder(self):
        '''获取福利院入住的长者信息'''
        _filter = self.___org_area_organization('福利院')
        _filter.inner_join_bill('PT_Hotel_Zone', 'user_info.id', 'organization_id', 'hotel_zone_info')\
               .inner_join_bill('PT_Bed', 'hotel_zone_info.id', 'area_id', 'bed_info')\
               .match((C('bed_info.residents_id') != None)|(C('bed_info.residents_id')!=''))\
               .inner_join_bill('PT_User', 'bed_info.residents_id', 'id', 'elder_info')
        return _filter
    
    def mega_sum(self,res):
        '''统计走势的函数'''
        s = 0
        for i in range(len(res)):
            s = s + res[i]
            res[i] = s
        return res

############################################公共部分###################################################################################################################

    def com_statistics_total_quantity(self, condition, page, count):
        '''按行政区划和用户类型统计幸福院数量'''
        _filter = self.___org_area_organization('幸福院')
        _filter.count('y')
        print('>>>>>>>>>>>>',_filter.filter_objects)
        res = self.query(_filter, self.business_area_collection)
        return res
    #success

    def org_map_location_welfare_centre(self, condition, page, count):
        '''机构养老 星空图'''
        _filter = self.___org_area_organization('福利院')
        _filter.group({'x':'$user_info.organization_info.lon','y':'$user_info.organization_info.lat','z': '$user_info.name','id':'$user_info.id'}, [{'value': self.ao.summation(1)}])
        res = self.query(_filter, self.business_area_collection)

        # 呼叫中心测试代码
        caller_collection = 'PT_Call_Record'
        _filter_caller = MongoBillFilter()
        # TODO: 1、号码不唯一，怎么处理 2、长者信息里没有位置的话，需要一个默认弹框位置
        _filter_caller.match((C('call_status') == 1))\
            .lookup('PT_User', 'phone', 'telephone', "user_info")\
            .add_fields({
                'name':'$user_info.name',
                'sex':'$user_info.personnel_info.sex',
                'x':"$user_info.personnel_info.lon",
                'y':'$user_info.personnel_info.lat',
                'address':'$user_info.address'
                # 'phone':'phone'
            })\
            .unwind('name')\
            .unwind('x')\
            .unwind('y')\
            .unwind('sex')\
            .unwind('address')\
            .project({'user_info._id':0, '_id':0})
        res_caller = self.query(_filter_caller, caller_collection)

        # 计算年龄
        for result in res_caller:
            # TODO: userinfo是不是只有一个数组？？？
            id_card = result['user_info'][0].get('id_card')
            if id_card:
                if len(id_card) == 18:
                    get_infomation_by_idcard = GetInformationByIdCard(id_card)
                    result['age'] = get_infomation_by_idcard.get_age() 

        result = [
            {
                'mapType':'scatter',
                'name':'星空图',
                'data':res,
            },
            {
                'mapType':'call',
                'name':'长者呼叫',
                'data':res_caller,
            }
        ]
        return result         
    #success

    def com_detail_total_quantity(self,condition,page,count):
        '''社区养老 明细 总服务次数'''
        _filter = self.___current_user(condition)
        _filter.inner_join_bill('PT_Service_Order','id','service_provider_id','service_order')\
            .inner_join_bill('PT_Service_Record','service_order.id','order_id','service_record')\
            .group({'record':'$service_record.id'}).count('y')
        res = self.query(_filter,'PT_User')
        return res
    # success
        
    def org_detail_service_personal_total_quantity(self,condition,page,count):
        '''社区养老 明细 总服务人数'''
        _filter = self.___current_user(condition)
        _filter.inner_join_bill('PT_Service_Order','id','service_provider_id','service_order')\
            .inner_join_bill('PT_Service_Record','service_order.id','order_id','service_record')\
            .group({'record':'$service_order.service_provider_id'}).count('y')
        res = self.query(_filter,'PT_User')
        return res
    # success
    
    def com_statistics_service_quantity(self,condition,page,count):
        '''社区养老 统计 幸福院服务总次数'''
        _filter = self.___org_area_organization('幸福院')
        _filter.inner_join_bill('PT_Service_Order','user_info.id','service_provider_id','service_order')\
            .inner_join_bill('PT_Service_Record','service_order.id','order_id','service_record')
        _filter.count('y')
        res = self.query(_filter, self.business_area_collection)
        res2 = self.com_statistics_total_quantity(condition, page, count)
        return res +res2
    # success

    def com_statistics_service_personal_quantity(self,condition,page,count):
        '''社区养老 统计 服务人员总人数'''
        _filter=self.___org_area_organization('幸福院')
        _filter.inner_join_bill('PT_User_Relationship','user_info.id','main_relation_people','relationship')\
            .inner_join_bill('PT_User_Relationship_Type','relationship.relationship_type_id','id','relation_type')\
            .match((C('relation_type.name') == '雇佣'))\
            .group({'x':'$relationship.subordinate_relation_people'}).count('y')
        res = self.query(_filter, self.business_area_collection)
        res2 = self.com_statistics_total_quantity(condition, page, count)
        return res + res2
    # success

    def com_statistics_nature_quantity(self,condition,page,count):
        '''社区养老 统计 幸福院数量（性质）'''
        _filter = self.___org_area_organization('幸福院')
        _filter.group({'x':'$user_info.organization_info.organization_nature'},[{'y':self.ao.summation(1)}])
        res = self.query(_filter,self.business_area_collection)
        return res
    #success
    def com_statistics_star_quantity(self,condition,page,count):
        '''社区养老 统计 幸福院数量（星级）'''
        _filter = self.___org_area_organization('幸福院')
        _filter.inner_join('PT_Qualification_Type','user_info.qualification_info.qualification_type_id','id','qualification_type')\
            .match(C('qualification_type.name') == '服务评级')\
            .add_fields({'level':'$user_info.qualification_info'})\
            .unwind('level')\
            .group({'x':'$level.name'},[{'y':self.ao.summation(1)}])
        res = self.query(_filter,self.business_area_collection)
        return res
    #success

    def com_statistics_service_provider_quantity(self,condition,page,count):
        '''社区养老 统计 幸福院数量（经营服务商）'''
        _filter = self.___org_area_organization('幸福院')
        _filter.inner_join_bill('PT_User_Relationship','user_info.id','subordinate_relation_people','relationship')\
            .inner_join_bill('PT_User_Relationship_Type','relationship.relationship_type_id','id','relation_type')\
            .lookup_bill('PT_User','relationship.main_relation_people','id','service_provider')\
            .add_fields({'service_provider_name':'$service_provider.organization_info.name'})\
            .match((C('relation_type.name') == '所属'))\
            .group({'x': '$service_provider_name'}, [{'y': self.ao.summation(1)}])
        print('<<<<<<<<<<<<<<<<<<<<<<<<<',_filter.filter_objects)
        res = self.query(_filter,self.business_area_collection)
        res_list = self.___list_transform(res)
        return res_list
    # success


    
    def com_statistics_community_score(self,condition,page,count):
        '''社区养老 统计 服务评分(幸福院)'''
        _filter = self.___org_area_organization('幸福院')
        _filter.inner_join_bill('PT_Service_Order','user_info.id','service_provider_id','order_info')\
            .inner_join_bill('PT_Service_Record','order_info.id','order_id','service_record')\
            .unwind('service_record.appraise_list')\
            .add_fields({'score':'$service_record.appraise_list.score'})\
            .group({'x':'$user_info.name'},[{'y':self.ao.avg('$score')}]).sort({'y':-1}).limit(10)
        res = self.query(_filter,self.business_area_collection)
        return res
    # sucess
    def com_statistics_org_score(self,condition,page,count):
        '''社区养老 统计 服务评分(运营机构)'''
        _filter = self.___org_area_organization('幸福院')
        _filter.inner_join_bill('PT_User_Relationship','user_info.id','main_relation_people','relationship')\
            .inner_join_bill('PT_User_Relationship_Type','relationship.relationship_type_id','id','relation_type')\
            .inner_join_bill('PT_User','relationship.relationship.subordinate_relation_people','id','org')\
            .inner_join_bill('PT_Service_Record','user_info.id','servicer_id','service_record')\
            .unwind('service_record.appraise_list')\
            .add_fields({'score':'$service_record.appraise_list.score'})\
            .match((C('relation_type.name') == '所属'))\
            .group({'x':'$org.name'},[{'y':self.ao.avg('$score')}]).sort({'y':-1}).limit(10)
        res = self.query(_filter,self.business_area_collection)
        return res
    #
    def com_statistics_service_personal_score(self,condition,page,count):
        '''社区养老 统计 服务评分(服务人员)'''
        _filter = self.__com_stat_service_record()
        _filter.add_fields({'score':self.ao.avg('$service_record.appraise_list.score')})\
            .inner_join_bill("PT_User",'service_record.servicer_id','id','servicer_info')\
            .group({'x':'$servicer_info.name'},[{'y':self.ao.avg('$score')}]).limit(12)
        res = self.query(_filter,self.business_area_collection)
        return res
    # success
    
    def com_statistics_type_activity_quantity(self,condition,page,count):
        '''社区养老 统计 活动次数(活动类型)'''
        _filter = self.___org_area_organization('幸福院')
        _filter.lookup('PT_Activity','user_info.id','organization','activity_info')\
            .inner_join('PT_Activity_Type','activity_info.activity_type_id','id','activity_type')\
            .add_fields({'type_name':'$activity_type.name'})\
            .group({'x':'$type_name'},[{'y':self.ao.summation(1)}])
        res = self.query(_filter,self.business_area_collection)
        return res   
    #  success

    def com_statistics_sex_activity_quantity(self,condition,page,count):
        '''社区养老 统计 活动次数(长者性别)'''
        _filter = self.___org_area_organization('幸福院')
        _filter.inner_join('PT_Activity','user_info.id','organization','activity')\
            .inner_join('PT_Activity_Sign_In','activity.id','activity_id','sign_in')\
            .inner_join_bill('PT_User','sign_in.user_id','id','elder_info')\
            .add_fields({'type_name':'$activity_type.name'})\
            .group({'x':'$elder_info.personnel_info.sex'},[{'y':self.ao.summation(1)}])
        res = self.query(_filter,self.business_area_collection)
        return res 
    # success

    def com_statistics_age_activity_quantity(self,condition,page,count):
        '''社区养老 统计 活动次数(年龄段)'''
        _filter = self.___org_area_organization('幸福院')
        _filter.inner_join('PT_Activity','user_info.id','organization','activity')\
            .inner_join('PT_Activity_Participate','activity.id','activity_id','participate')\
            .inner_join_bill('PT_User','participate.user_id','id','elder')\
            .add_fields({'birth_year': self.ao.year('$elder.personnel_info.date_birth')})
        _filter = self.__elder_group_by_age(_filter)
        _filter.group({'x': '$age_range'},[{'y':self.ao.summation(1)}]).sort({'x':1})
        res = self.query(_filter,self.business_area_collection)
        return res
    # success

    def com_statistics_education_activity_quantity(self,condition,page,count):
        '''社区养老 统计 活动次数(学历)'''
        _filter = self.___org_area_organization('幸福院')
        _filter.inner_join('PT_Activity','user_info.id','organization','activity')\
            .inner_join('PT_Activity_Participate','activity.id','activity_id','participate')\
            .inner_join_bill('PT_User','participate.user_id','id','elder')\
            .unwind('elder.qualification_info')\
            .inner_join('PT_Qualification_Type','elder.qualification_info.qualification_type_id','id','qualification_type')\
            .match(C('qualification_type.name').like('学历'))\
            .add_fields({'qualification_info_name':'$elder.qualification_info.name'})\
            .group({'x':'$qualification_info_name'},[{'y':self.ao.summation(1)}])
        print(_filter.filter_objects)
        res = self.query(_filter,self.business_area_collection)
        res = self.___list_transform(res)
        return res
    #  success

    def com_statistics_education_attend_class_quantity(self,condition,page,count):
        '''社区养老 统计 上课次数(学历)'''
        _filter = self.___com_stat_service()
        _filter.inner_join_bill('PT_User','service_order.purchaser_id','id','elder')\
            .inner_join_bill('PT_Qualification_Type','elder.qualification_info.qualification_type_id','id','qualification_type')\
            .match((C('service_type.name') == '教育') & (C('qualification_type.name') == '学历证明'))\
            .group({'x':'$elder.qualification_info.name'},[{'y':self.ao.summation(1)}])
        res = self.query(_filter,self.business_area_collection)
        return res
    # success
    def com_statistics_curriculum_attend_class_quantity(self,condition,page,count):
        '''社区养老 统计 上课次数(课程)'''
        _filter = self.___com_stat_service()
        _filter.match((C('service_type.name') == '教育'))\
            .group({'x':'$service_product.name'},[{'y':self.ao.summation(1)}])
        res = self.query(_filter,self.business_area_collection)
        return res
    # suceess
    def com_statistics_curriculum_type_attend_class_quantity(self,condition,page,count):
        '''社区养老 统计 上课次数(课程分类)'''
        _filter = self.___com_stat_service()
        _filter.match((C('service_type.name') == '教育'))\
            .group({'x':'$service_item.name'},[{'y':self.ao.summation(1)}])
        res = self.query(_filter,self.business_area_collection)
        return res
    # success

    def com_statistics_community_meals_quantity(self,condition,page,count):
        '''社区养老 统计 长者饭堂用餐人次(幸福院)'''
        _filter = self.___com_stat_service()
        _filter.match((C('service_type.name') == '用餐'))\
            .group({'x':'$user_info.name'},[{'y':self.ao.summation(1)}])
        res = self.query(_filter,self.business_area_collection)
        return res
    # success
    
    def com_statistics_service_provider_meals_quantity(self,condition,page,count):
        '''社区养老 统计 长者饭堂用餐人次(服务商)'''
        _filter = self.___com_stat_service()
        _filter.inner_join_bill('PT_User_Relationship','user_info.id','main_relation_people','relationship_info')\
            .inner_join_bill('PT_User_Relationship_Type','relationship_info.relationship_type_id','id','relationship_type')\
            .inner_join_bill("PT_User",'relationship_info.subordinate_relation_people','id','service_provider')\
            .match_bill((C('service_type.name') == '用餐') & (C('relationship_type.name') == '所属'))\
            .group({'x':'$service_provider.name'},[{'y':self.ao.summation(1)}]).limit(10)
        print(_filter.filter_objects)
        res = self.query(_filter,self.business_area_collection)
        return res
    # success
    def com_statistics_community_happiness_station_quantity(self,condition,page,count):
        '''社区养老 统计  幸福小站使用次数（幸福院）'''
        _filter = self.___com_stat_service()
        _filter.match_bill((C('service_item.name').like('幸福小站')))\
            .group({'x':'$user_info.name'},[{'y':self.ao.summation(1)}]).limit(10)
        res = self.query(_filter,self.business_area_collection)
        return res
    # success

    def org_card_location_welfare_centre(self,condition,page,count):
        '''机构养老 地图 卡片（当前福利院信息）'''
        _filter = self.___org_area_organization('福利院')
        _filter.lookup_bill('PT_Hotel_Zone', 'user_info.id', 'organization_id', 'hotel_zone_info')\
            .lookup_bill('PT_Bed','hotel_zone_info.id','area_id','bed_info')\
            .add_fields({'bed_person':self.ao.array_filter('$bed_info','a',(F('$a.residents_id')!='').f)})\
            .inner_join('PT_Qualification_Type','user_info.qualification_info.qualification_type_id','id','qualification_type')\
            .match((C('qualification_type.name') == '服务评级'))\
            .add_fields({'qualification_level':'$user_info.qualification_info.qualification_level'})\
            .project({'_id':0,'y1':'$user_info.organization_info.name','y2':self.ao.size('$bed_person'),
                'y3':'$user_info.qualification_info.qualification_level',
                'y4':'$user_info.organization_info.personnel_category',
                'y5':'$user_info.organization_info.organization_nature',
                'y6':'$user_info.organization_info.legal_person',
                'y7':'$user_info.address',
                'y8':'$user_info.organization_info.telephone',
                'x1':'$user_info.organization_info.lon',
                'x2':'$user_info.organization_info.lat'})
        res = self.query(_filter, self.business_area_collection)
        res = self.___list_transform(res)
        return res   
    # success  

    def com_detail_picture_list(self,condition,page,count):
        '''社区养老 明细 图片列表'''
        _filter = self.___com_detail_org(condition)
        _filter.inner_join_bill('PT_Multi_Media','id','link_obj_id','media_info')\
            .match_bill(C('media_info.media_type') == '图片')\
            .project({'y':'$media_info.content_url','_id':0})
        res = self.query(_filter,'PT_User')
        res_list = self.___create_list(res)
        return res_list
    #success
    def com_detail_activity_picture_list(self,condition,page,count):
        '''社区养老 明细 活动图片列表''' 
        _filter = self.___com_detail_org(condition)
        _filter.inner_join('PT_Activity','id','organization','activity_info')\
            .project({'_id':0,'y':'$activity_info.photo'})
        res = self.query(_filter,'PT_User')
        res_list = self.___create_list(res)
        result_list = []
        if res_list:
            for x in res_list:
                result_list.extend(x)
        else:
            return res_list
        return result_list
    # success


    def com_detail_video_surveillance(self,condition,page,count):
        '''社区养老 明细 摄像头列表（视频监控）'''
        _filter = self.___com_detail_org(condition)
        _filter.inner_join('PT_Monitor','id','link_obj_id','molitor_info')\
            .project({'_id':0,'y':'$molitor_info.url'})
        res = self.query(_filter,'PT_User')
        res_list = self.___create_list(res)
        return res_list
    #  success 

    def com_detail_personal_list(self,condition,page,count):
        '''社区养老 明细 人员风采轮播 '''
        _filter = self.___com_detail_org(condition)
        _filter.inner_join_bill('PT_User_Relationship','id','main_relation_people','relationship_info')\
                .inner_join_bill('PT_User_Relationship_Type','relationship_info.relationship_type_id','id','relationship_type')\
                .inner_join_bill("PT_User",'relationship_info.subordinate_relation_people','id','service_person')\
                .inner_join('PT_Qualification_Type','qualification.qualification_type_id','id','qualification_type')\
                .match((C('relationship_type.name') == '雇佣') & (C('qualification_type.name') == '服务评级'))\
                .project({"_id":0,'y1':'$service_person.content','x':'$service_person.personnel_info.photo','y2':'$service_person.qualification_info.name','y3':'$service_person.qualification_info.name'})
        res = self.query(_filter,'PT_User')
        result = self.___list_transform(res)
        return result
    #列表型 success

    def com_detail_activity(self,condition,page,count):
        '''社区养老 明细 最新活动情况 '''
        _filter = self.___com_detail_org(condition)
        _filter.inner_join('PT_Activity','id','organization','activity_info')\
            .lookup('PT_Activity_Participate','activity_info.id','activity_id','participate_info')\
            .sort({'activity_info.begin_date':-1})\
            .limit(1)\
            .add_fields({'count':self.ao.size('$participate_info.user_id')})\
            .project({'_id':0,'y1':'$activity_info.activity_name','y2':'','y3':'$activity_info.begin_date','y4':'$count','x':'$activity_info.photo'})
        res = self.query(_filter,'PT_User')
        return res
    # success
    def com_detail_service_price_picture(self,condition,page,count):
        '''社区养老 明细 服务价格表'''
        _filter = self.___com_detail_org(condition)
        _filter.inner_join('PT_Multi_Media','id','link_obj_id','media')\
            .match(C('media.classification').like('服务价格表'))\
            .project({'_id':0,'y':'$media.content_url'})
        print(_filter.filter_objects)
        res = self.query(_filter,'PT_User')
        res_list = self.___create_list(res)
        return res_list
    #success

    def com_detail_service_products_list(self,condition,page,count):
        '''社区养老 明细 服务产品清单'''
        _filter = self.___com_detail_org(condition)
        _filter.inner_join_bill('PT_Service_Product','id','org_id','service_product')\
            .match_bill(C('service_product.state') == '1')\
            .project({"_id":0,'y2':'$service_product.picture_collection','y1':'$service_product.name','x':'$service_product.service_product_introduce'})
        print(_filter.filter_objects)
        res = self.query(_filter,'PT_User')
        if res:
            for result in res:
                if result.get('y2'):
                    result['y2'] = result.get('y2')[0]
                else:
                    result['y2'] = 'https://www.baidu.com/link?url=I95KWgIS3jlw4_xb9hpj9JvZqzD35kCswSQYoIbnN1OGuEMaB4NgfaQvCthdqkkVQzyZ0UNUCFAEI4EE_jts-hYf10jc73aFJjo3pbYVfxeTwh15UCfbnXp2Rzr7dRj7ZSJ7ZPdeKQnpMPm9VwZqxl4ImqEgqG_jtkoOEfT5kQ4JbaeyIR_q8iKj5noS2_v17yvpo_4g4TSPMdRqDbHtqodbBzKQGq_zbuqjE7qIVqsSvlD7XdISDWY8i1e7J20DwbPmATMlR4drgs3yYFjt_2sHSUyEoCA7HjbsPfAJnqdasMknGtrSmZ0rUnKyX7RBNrKRHKcVEUSgbFMU7pffDAuvVtKBglz81nE55sK6VdifCGHxtUQHVk_5mNDFFBwgMS1CWiDKzAJrWWwT6DevTeO0Fh3QAzIkPVJglxSAlFJm7uJFS7PKXyeKmJL0Ghnt4-T5OS7Hte5VfDAYZtrO5eK8kNKpxWGB04lItFB8lqAIyFEWRTyrDeTwMSfaPZDYvpatBF-Q_f8WdGNgGgMGsTQAqa1tx7k0RRvBZUFMPMwSDUOD0SDdkEOx54uLnPaLjnLinoFnKqkOBaZMkMZw0b5IUw3ZIDOEC8JBxJ0FhnaB0li9KCeexK10Hbm6QrF0&timg=https%3A%2F%2Fss0.bdstatic.com%2F94oJfD_bAAcT8t7mm9GUKT-xh_%2Ftimg%3Fimage%26quality%3D100%26size%3Db4000_4000%26sec%3D1568707975%26di%3D66614f0f01d69d2aa2e25243c3889a59%26src%3Dhttp%3A%2F%2Fzwzx.cangzhou.gov.cn%2Fnewimages%2Fksry%2F1.jpg&click_t=1568707978725&s_info=1468_927&wd=&eqid=e7e3a9f30002e865000000065d809587'
        return res
    # success
    
    def com_detail_service_products(self,condition,page,count):
        '''社区养老 明细 服务产品介绍轮播'''
        _filter = self.___com_detail_org(condition)
        _filter.inner_join_bill('PT_Service_Product','id','org_id','service_product')\
            .match_bill(C('service_product.state') == '1')\
            .project({"_id":0,'y3':'$service_product.service_product_introduce','y1':'$service_product.name','y2':'$service_product.picture_collection'})
        res = self.query(_filter,'PT_User')
        return res
    # success

    def eld_map_location(self,condition,page,count):
        '''长者 地图 星空图和热力图''' 
        _filter_scatter = self.___get_elder()
        _filter_scatter.inner_join('PT_User_Current_Pos','user_info.id','user_id','user_current_pos')\
            .project({'_id':0,'z':"$user_info.personnel_info.name",'y':'$user_current_pos.lat','x':'$user_current_pos.lon','id':'$user_info.id'})
        res_scatter = self.query(_filter_scatter,self.business_area_collection) #星空图
        print(res_scatter)
        _filter_heatmap = self.___get_elder()
        _filter_heatmap.inner_join('PT_User_Current_Pos','user_info.id','user_id','user_current_pos')\
            .project({'_id':0,'y':'$user_current_pos.lat','x':'$user_current_pos.lon','id':'$user_info.id'})
        res_heatmap = self.query(_filter_heatmap,self.business_area_collection)# 热力图
        res = [{
                'mapType':'scatter',
                'data':res_scatter,
            },{
                'mapType':'heatMap',
                'data':res_heatmap,
                'count':len(res_heatmap)
            }]
        if condition.get('mapType') == 'scatter':
            res = [{
                'mapType':'scatter',
                'data':res_scatter,
            }]
        elif condition.get('mapType') == 'heatMap': 
            res = [{
                'mapType':'heatMap',
                'data':res_heatmap,
                'count':len(res_heatmap)
            }]
        return res
    # success
    def eld_card_location(self,condition,page,count):
        '''长者 卡片 当前长者信息'''
        _filter = self.___get_elder()
        _filter.lookup('PT_User_Current_Pos','user_info.id','user_id','user_current_pos')\
            .lookup_bill('PT_Bed','user_info.id','residents_id','bed_info')\
            .lookup_bill('PT_Hotel_Zone', 'bed_info.area_id', 'id', 'hotel_zone_info')\
            .lookup_bill('PT_User','hotel_zone_info.organization_id','id','org')\
            .unwind('org',True)\
            .project({'_id':0,'y1':'$user_info.personnel_info.name','y2':'$user_info.personnel_info.photo','y3':'$org.organization_info.name','y4':'$user_info.address','y5':'$user_info.personnel_info.telephone','x1':'$user_current_pos.lon','x2':'$user_current_pos.lat'})
        res = self.query(_filter,self.business_area_collection)
        res_list = self.___list_transform(res)
        return res_list
    #success

    def org_detail_profit_total_quantity(self,condition,page,count):
        '''社区养老 明细 服务总收益'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill(C('id')==values['id'])\
            .lookup_bill('PT_Service_Order','id','service_provider_id','service_order')\
            .inner_join_bill('PT_Service_Record','service_order.id','order_id','service_record')\
            .group({}, [{'y': self.ao.summation('$service_record.valuation_amount')}])
        res = self.query(_filter, 'PT_User')
        return res
    # success
    def com_map_location_community(self,condition,page,count):
        '''社区养老 星空图 幸福院'''
        _filter = self.___org_area_organization('幸福院')
        _filter.lookup_bill('PT_Qualification_Type','user_info.qualification_info.qualification_type_id','id','qualification_type')\
            .unwind('user_info.qualification_info')\
            .match((C('qualification_type.name') == '服务评级'))\
            .add_fields({'qualification_level':'$user_info.qualification_info.name'})\
            .project({"_id":0,'x':'$user_info.organization_info.lon','y':'$user_info.organization_info.lat','z':'$user_info.organization_info.name','value':'$qualification_level','id':'$user_info.id'})
        res = self.query(_filter,self.business_area_collection)
        result = [{
            'mapType':'scatter',
            'name':'星空图',
            'data':res,
        }]
        return result
    # success
    
    def com_card_location_community(self,condition,page,count):
        '''社区养老 卡片 当前幸福院信息'''
        _filter = self.___org_area_organization('幸福院')
        _filter.unwind('user_info.qualification_info')\
            .lookup_bill('PT_Qualification_Type','user_info.qualification_info.qualification_type_id','id','qualification_type')\
            .match((C('qualification_type.name') == '服务评级'))\
            .add_fields({'qualification_level_name':'$user_info.qualification_info.name'})\
            .project({'_id':0,
                'y1':'$user_info.organization_info.name',
                'y2':'$qualification_level_name',
                'y3':'$user_info.organization_info.personnel_category',
                'y4':'$user_info.organization_info.organization_nature',
                'y5':'$user_info.organization_info.legal_person',
                'y6':'$user_info.address',
                'y7':'$user_info.organization_info.telephone',
                'x1':'$user_info.organization_info.lon',
                'x2':'$user_info.organization_info.lat'})
        res = self.query(_filter,self.business_area_collection)
        res_list = self.___list_transform(res)
        return res_list
    # success
###########################################################调到这######################################################################
    def org_detail_community(self,condition,page,count):
        '''社区养老 明细 幸福院简介'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == values['id'])& (C('personnel_type') == UserType.Organizational) & (C('organization_info.personnel_category') == '幸福院'))\
            .lookup_bill('PT_User_Relationship','id','main_relation_people','relationship_info')\
            .lookup_bill('PT_User_Relationship_Type','relationship_info.relationship_type_id','id','relationship_type')\
            .add_fields({'worker':self.ao.array_filter('$relationship_info','a',(F('$a.subordinate_relation_people')!='').f)})\
            .lookup_bill('PT_Qualification_Type','qualification_info.qualification_type_id','id','qualification_type')\
            .match((C('qualification_type.name') == '服务评级') & (C('relationship_type.name') == '雇佣'))\
            .project({
            '_id':0,
            'y1':'$organization_info.name',
            'y2':'$address',
            'y3':self.ao.size('$worker'),
            'y5':'$organization_info.personnel_category',
            'y6':'$organization_info.organization_nature',
            'y7':'$organization_info.legal_person',
            'y8':'$organization_info.telephone',
            'x':'$content',
        })
        res = self.query(_filter,'PT_User')
        return res
    #success

    def com_statistics_time_sign_in_quantity(self,condition,page,count):
        '''社区养老 统计 长者签到人数（时间）'''
        _filter = self.___org_area_organization('幸福院')
        _filter.inner_join('PT_Activity','user_info.id','organization','activity')\
            .inner_join('PT_Activity_Sign_In','activity.id','activity_id','act_sign_in')\
            .inner_join_bill('PT_User','act_sign_in.user_id','id','elder_info')
        _filter_new = self._group_by_date(_filter,'$act_sign_in.date','月')
        _filter_new.group({'x':'$new_date'},[{'y':self.ao.summation(1)}]).sort({'x':1})
        res = self.query(_filter,self.business_area_collection)
        return res 
    #success
    def com_statistics_time_activity_quantity(self,condition,page,count):
        '''社区养老 统计 活动数量（时间）'''
        _filter = self.___org_area_organization('幸福院')
        _filter.inner_join('PT_Activity','user_info.id','organization','activity')
        _filter_new = self._group_by_date(_filter,'$activity.begin_date','月')
        _filter_new.group({'x':'$new_date'},[{'y':self.ao.summation(1)}]).sort({'x':1})
        res = self.query(_filter,self.business_area_collection)
        return res
    # success
    def com_statistics_time_meals_quantity(self,condition,page,count):
        '''社区养老 统计 长者饭堂用餐人数（时间）'''
        _filter = self.___com_stat_service()
        # _filter = self.___org_area_organization('幸福院')
        _filter.inner_join_bill('PT_User','service_order.purchaser_id','id','elder_info')\
            .match((C('service_type.name') == '用餐'))
        _filter_new = self._group_by_date(_filter,'$service_record.start_date','月')
        _filter_new.group({'x':'$new_date'},[{'y':self.ao.summation(1)}]).sort({'x':1})
        print(_filter.filter_objects)
        res = self.query(_filter,self.business_area_collection)
        return res
    # success

    def com_statistics_time_education_quantity(self,condition,page,count):
        '''社区养老 统计 长者教育人数（时间）'''
        _filter = self.___com_stat_service()
        _filter.inner_join_bill('PT_User','service_order.purchaser_id','id','elder_info')\
            .match((C('service_type.name') == '教育'))
        _filter_new = self._group_by_date(_filter,'$service_record.start_date','月')
        _filter_new.group({'x':'$new_date'},[{'y':self.ao.summation(1)}]).sort({'x':1})
        print(_filter_new.filter_objects)
        res = self.query(_filter_new,self.business_area_collection)
        return res
    #success

    def com_statistics_time_activity_personal_quantity(self,condition,page,count):
        '''社区养老 统计 活动平均人数（时间）'''
        _filter = self.___org_area_organization('幸福院')
        _filter.inner_join('PT_Activity','user_info.id','organization','activity')\
            .lookup('PT_Activity_Participate','activity.id','activity_id','participate')\
            .lookup_bill('PT_User','participate.user_id','id','people_info')\
            .add_fields({'par_people':self.ao.size('$people_info')})
        _filter_new = self._group_by_date(_filter,'$activity.begin_date','月')
        _filter_new.group({'x':'$new_date'},[{'y':self.ao.avg('$par_people')}]).sort({'x':1})
        print(_filter.filter_objects)
        res = self.query(_filter,self.business_area_collection)
        if res:
            for result in res:
                result['y'] = round(float(result.get('y')),2)
        return res
    # success

    def com_statistics_street_quantity(self,condition,page,count):
        '''社区养老 统计 幸福院数量（镇街）'''
        _filter = self.___org_area_organization('幸福院')
        _filter.group({'x':'$user_info.town'},[{'y':self.ao.summation(1)}]).limit(10)
        res = self.query(_filter,self.business_area_collection)
        return res
    # success

    def spe_statistics_type_service_personal_quantity(self,condition,page,count):
        '''服务人员 统计 服务人员数量（证件类型）'''
        _filter = self.__sep_stat_service_person()
        _filter.group({'x':'$servicer_info.personnel_info.id_card_type'},[{'y':self.ao.summation(1)}])
        res = self.query(_filter,self.business_area_collection)
        return res
    # suucess

    def spe_statistics_source_service_personal_quantity(self,condition,page,count):
        '''服务人员 统计 服务人员数量（来源）'''
        _filter = self.__sep_stat_service_person()
        _filter.group({'x':'$servicer_info.town'},[{'y':self.ao.summation(1)}]).limit(10)
        res = self.query(_filter,self.business_area_collection)
        return res
    #success

    def spe_card_location(self,condition,page,count):
        '''服务人员 地图 当前服务人员信息（卡片）'''
        _filter = self.__sep_stat_service_person()
        _filter.lookup_bill('PT_Qualification_Type','servicer_info.qualification_info.qualification_type_id','id','qualification_type')\
            .lookup('PT_User_Current_Pos','servicer_info.id','user_id','current_pos_info')\
            .match((C('qualification_type.name') == '服务评级'))\
            .project({"_id":0,
                'y1':'$servicer_info.personnel_info.name',
                'y2':'$servicer_info.personnel_info.photo',
                'y3':'$user_info.organization_info.name',
                'y4':'$user_info.qualification_info.qualification_level',
                'y5':'$user_info.address',
                'y6':'$user_info.organization_info.telephone',
                'x1':'$current_pos_info.lon',
                'x2':'$current_pos_info.lat'})
        res = self.query(_filter,self.business_area_collection)
        result = self.___list_transform(res)
        return result
    #success
    def spe_map_location(self,condition,page,count):
        '''服务人员 地图 星空图（服务人员）'''
        _filter = self.__sep_stat_service_person()
        _filter.inner_join('PT_User_Current_Pos','servicer_info.id','user_id','current_pos_info')\
            .project({"_id":0,
                'z':'$servicer_info.personnel_info.name',
                'x':'$current_pos_info.lon',
                'y':'$current_pos_info.lat',
                'id':'$servicer_info.id'})
        res = self.query(_filter,self.business_area_collection)
        result = self.___list_transform(res)
        res_re = [{
                'mapType':'scatter',
                'data':result,
            },]
        return res_re
    # success

    def spe_detail_task_card(self,condition,page,count):
        ''' 服务人员 明细 当前任务卡片'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id')==values['id']) &  (C('personnel_type') == UserType.Personnel))\
            .lookup_bill('PT_Task','id','task_receive_person','task_info')\
            .unwind('task_info')\
            .lookup_bill('PT_Service_Record','task_info.task_service_record_id','id','record_info')\
            .inner_join_bill('PT_Service_Order','record_info.order_id','id','order_info')\
            .lookup_bill('PT_User','order_info.purchaser_id','id','purchaser_info')\
            .inner_join_bill('PT_User','order_info.service_provider_id','id','provider_info')\
            .lookup_bill('PT_Service_Product','record_info.service_product_id','id','product_info')\
            .sort({'task_info.task_notice_time':-1})\
            .limit(1)\
            .project({'_id':0,'y1':'$task_info.task_code','y2':'$product_info.name','y3':'$task_info.task_address','y4':'$task_info.task_notice_time','y5':'$provider_info.name','y6':'$purchaser_info.name','y7':'$personnel_info.name'})
        res = self.query(_filter,'PT_User') 
        result = self.___list_transform(res)
        return result
    #success
    def spe_detail_live_video(self,condition,page,count):
        '''服务人员 明细 服务现场视频'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id')==values['id']) & (C('personnel_type') == UserType.Personnel))\
            .lookup_bill('PT_Service_Record','id','servicer_id','record_info')\
            .inner_join_bill('PT_Multi_Media','record_info.id','link_obj_id','media_info')\
            .match((C('media_info.media_type').like('视频')))\
            .project({'_id':0,'y':'$media_info.content_url'})
        res = self.query(_filter,'PT_User')
        return res
    #success
    def eld_detail_task_map(self,condition,page,count):
        '''长者 明细 当前任务地图'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill(C('id')==values['id'])\
            .inner_join_bill('PT_Service_Order','id','purchaser_id','order_info')\
            .inner_join_bill('PT_Service_Record','order_info.id','order_id','record_info')\
            .inner_join_bill('PT_Task','record_info.id','task_process_record.id','task_info')\
            .inner_join_bill('PT_User_Current_Pos','record_info.servicer_id','servicer_current_pos')\
            .unwind('$task_info.task_handler_travel')\
            .sort({'$task_info.task_notice_time':-1})\
            .limit(1)\
            .project({'_id':0,'y1':'$task_handler_travel.lon','y2':'$task_handler_travel.lat','y3':''})

    def eld_detail_elder_map(self,condition,page,count):
        '''长者 明细 长者地图'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id')==values['id']) & (C('personnel_type') == UserType.Personnel ))\
            .inner_join('PT_User_Current_Pos','id','user_id','servicer_current_pos')\
            .sort({'servicer_current_pos.update_time':-1})\
            .project({'_id':0,'y1':'$servicer_current_pos.lon','y2':'$servicer_current_pos.lat'})
        res = self.query(_filter,'PT_User')
        return res
    #success

    def eld_detail_activity_picture_list(self,condition,page,count):
        '''长者 明细 活动照片轮播'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill(C('id')==values['id'])\
            .inner_join('PT_Activity_Participate','id','user_id','participate_info')\
            .inner_join('PT_Activity','participate_info.activity_id','id','activity_info')\
            .project({'_id':0,'y':'$activity_info.photo'})
        res = self.query(_filter,'PT_User')
        return res
    # success

    def spe_detail_card(self,condition,page,count):
        '''服务人员 明细 服务人员简介'''
        _filter = self.___current_user(condition)
        _filter.lookup_bill('PT_User_Relationship','id','subordinate_relation_people','relationship_info')\
            .lookup_bill('PT_User_Relationship_Type','relationship_info.relationship_type_id','id','relationship_type')\
            .lookup("PT_User",'relationship_info.main_relation_people','id','org_info')\
            .unwind('qualification_info')\
            .inner_join_bill('PT_Qualification_Type','qualification_info.qualification_type_id','id','qualification_type')\
            .match((C('relationship_type.name') == '雇佣') & (C('qualification_type.name').like('评级')))\
            .project({'_id':0,'x':'$content','y1':'$personnel_info.photo','y2':'$qualification_info.name','y3':'$qualification_type.name','y4':'$org_info.name'})
        res = self.query(_filter,'PT_User')
        res_list = self.___list_transform(res)
        return res_list
    #success

    def spe_detail_picture_list(self,condition,page,count):
        '''服务人员 明细 图片列表'''
        _filter = self.___current_user(condition)
        _filter.match((C('personnel_type') == UserType.Personnel) & (C('personnel_info.personnel_category') == '工作人员'))\
            .inner_join('PT_Multi_Media','id','link_obj_id','media_info')\
            .match((C('media_info.media_type') == '图片'))\
            .project({'_id':0,'y':'$media_info.content_url'})
        print()
        res = self.query(_filter,'PT_User')
        res_list = self.___create_list(res)
        return res_list
    # success
    def spe_detail_activity_picture_list(self,condition,page,count):
        '''服务人员 明细 活动图片列表'''
        _filter = self.___current_user(condition)
        _filter.inner_join('PT_Activity_Participate','id','user_id','act_participate')\
            .inner_join('PT_Activity','act_participate.activity_id','id','activity')\
            .project({'_id':0,'y':'$activity.photo'})
        res = self.query(_filter,'PT_User')
        # res_list = self.___create_list(res)
        # if res_list:
        #     r_list = []
        #     for result in res_list:
        #         r_list.extend(result)
        return res
    # success

    def spe_detail_service_record_top10_list(self,condition,page,count):
        '''服务人员 明细 服务记录列表（TOP10）'''
        _filter = self.___current_user(condition)
        _filter.inner_join_bill('PT_Service_Record','id','servicer_id','record_info')\
            .inner_join_bill('PT_Service_Product','record_info.service_product_id','id','product_info')\
            .sort({'record_info.start_date':-1})\
            .limit(10)\
            .project({'_id':0,'y1':'$record_info.start_date','y2':'$product_info.name','y3':'$record_info.appraise_list.content'})
        res = self.query(_filter,'PT_User')
        res_list = self.___list_transform(res)
        result_list = self.___list_transform(res_list)
        return result_list
    # success

    def cop_detail_task_map(self,condition,page,count):
        '''综合 明细 当前任务地图'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill(C('id') == values['id'])\
            .lookup_bill('PT_Service_Record','task_service_record_id','id','record_info')\
            .lookup_bill('PT_User','record_info.servicer_id','id','servicer_info')\
            .lookup('PT_User_Current_Pos','servicer_info.id','user_id','current_pos_info')\
            .project({'_id':0,'y1':'$current_pos_info.lon','y2':'$current_pos_info.lat','y3':'$task_handler_travel'})
        res = self.query(_filter,'PT_Task')
        res_list = self.___list_transform(res)
        return res_list
    #success
##################迁移
    def cop_detail_live_video(self,condition,page,count):
        '''综合 明细 服务现场视频'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id')==values['id']))\
            .inner_join('PT_Multi_Media','id','link_obj_id','media_info')\
            .match((C('media_info.media_type').like('视频')))\
            .project({'_id':0,'y':'$media_info.content_url'})
        res = self.query(_filter,'PT_Service_Record')
        return res
    
    def spe_detail_task_map(self,condition,page,count):
        '''服务人员 明细 当前任务地图'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill(C('id') == values['id'])\
            .lookup_bill('PT_Service_Record','id','servicer_id','record_info')\
            .lookup_bill('PT_Task','record_info.id','task_service_record_id','task_info')\
            .lookup('PT_User_Current_Pos','id','user_id','current_pos_info')\
            .project({'_id':0,'y1':'$current_pos_info.lon','y2':'$current_pos_info.lat','y3':'$task_info.task_handler_travel'})
        res = self.query(_filter,'PT_User')
        res_list = self.___list_transform(res)
        return res_list  

    def spe_detail_service_personal_map(self,condition,page,count):
        '''服务人员 明细 服务人员地图'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill(C('id') == values['id'])\
            .lookup_bill('PT_Service_Record','id','servicer_id','record_info')\
            .lookup_bill('PT_Task','record_info.id','task_service_record_id','task_info')\
            .lookup('PT_User_Current_Pos','id','user_id','current_pos_info')\
            .unwind('task_info.task_handler_travel')\
            .project({'_id':0,'x':'$task_info.task_handler_travel.lon','y':'$task_info.task_handler_travel.lat'})
        print(_filter.filter_objects)
        res = self.query(_filter,'PT_User')
        res_list = self.___list_transform(res)
        result = [{
                'mapType':'scatter',
                'data':res_list,
        }]
        return result  

    def spe_detail_income_quantity(self, condition, page, count):
        '''服务人员-明细-总服务收入'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id')==values['id']) & (C('personnel_type') == '1'))\
                .inner_join_bill('PT_Service_Record','id','servicer_id','record_info')\
                .group({},[{'y': self.ao.summation('$record_info.valuation_amount')}])
        res = self.query(_filter,'PT_User')
        return res     

    def spe_detail_evaluate_quantity(self, condition, page, count):
        '''服务人员-明细-总服务评分'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id')==values['id']) & (C('personnel_type') == '1'))\
                .inner_join_bill('PT_Service_Record','id','servicer_id','record_info')\
                .unwind('record_info.appraise_list')\
                .project({"_id":0,'y':'$record_info.appraise_list.content'})
        res = self.query(_filter,'PT_User')
        return res    

    def spe_detail_total_quantity(self, condition, page, count):
        '''服务人员-明细-总服务次数'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill(C('id')==values['id'])\
            .inner_join_bill("PT_Service_Record",'id','servicer_id','record_info')\
                .count('y')
        res = self.query(_filter,'PT_User')
        return res
    
    def eld_detail_service_live_video_card(self, condition, page, count):
        '''长者 明细 服务现场视频'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id')==values['id']) & (C('personnel_type') == UserType.Personnel))\
            .lookup_bill("PT_Service_Order",'id','purchaser_id','order_info')\
            .lookup_bill('PT_Service_Record','order_info.id','order_id','record_info')\
            .lookup('PT_Multi_Media','record_info.id','link_obj_id','media_info')\
            .match((C('media_info.media_type').like('视频')))\
            .project({'_id':0,'y':'$media_info.content_url'})
        print(_filter.filter_objects)
        res = self.query(_filter,'PT_User')
        return res
    
    def spe_detail_total_service_person(self, condition, page, count):
        '''服务人员-明细-总服务人次'''
        keys = ['id']
        values = self.get_value(condition,keys)
        _filter = MongoBillFilter()
        _filter.match_bill(C('id')==values['id'])\
                .group({},[{'y':self.ao.summation(1)}])\
                .count('y')
        res = self.query(_filter,'PT_Service_Record')
        return res
    
    def eld_statistics_condition_elder_quantity(self, condition, page, count):
        '''长者 统计 长者数量（病情）'''
        _filter = self.__eld_area_basic()
        _filter.inner_join('PT_Disease_Record','user_info.id','user_id','disease_record')\
            .inner_join('PT_Disease_Type','disease_record.disease_type_id','id','disease_type')\
            .group({'x': '$disease_type.name'},[{'y':self.ao.summation(1)}]).limit(10)
        res = self.query(_filter,self.business_area_collection)
        return res
    # success
    def eld_statistics_subsidy_elder_quantity(self, condition, page, count):
        '''长者 统计 长者数量（补贴类型）'''
        _filter = self.__eld_area_basic()
        _filter.inner_join('PT_Social_Groups_Type','user_info.personnel_info.social_groups_type_id','id','social_groups_type')\
            .group({'x': '$social_groups_type.name'},[{'y':self.ao.summation(1)}])
        res = self.query(_filter,self.business_area_collection)
        new_list = []
        if res:
            A = 0
            B = 0
            C = 0    
            for result in res:
                if 'A' in result.get('x'):
                    A += int(result.get('y'))
                elif 'B' in result.get('x'):
                    B += int(result.get('y'))
                elif 'C' in result.get('x'):
                    C += int(result.get('y'))
                else:
                    new_list.append(result)
            new_list.append({'x':'A','y':A})
            new_list.append({'x':'B','y':B})
            new_list.append({'x':'C','y':C})
        return new_list
    # success

    def org_statistics_children_personnel_quantity(self, condition, page, count):
        '''机构养老-长者数量-子女情况'''
        _filter = self.__org_stat_elder()
        _filter.lookup_bill('PT_User_Relationship', 'elder_info.id', 'main_relation_people', 'relation_info')\
               .inner_join_bill('PT_User_Relationship_Type', 'relation_info.relationship_type_id', 'id', 'relation_type_info')\
               .match(C('relation_type_info.name') == '子女')\
               .add_fields({'count':self.ao.size('$relation_info')})\
               .group({'x':'$count'},[{'y':self.ao.summation(1)}])
        res = self.query(_filter, self.business_area_collection)
        def get_key(a):
            return a.get('x')
        res.sort(key=get_key)
        return res
    
    def org_statistics_time_income_quantity(self, condition, page, count):
        '''机构养老 统计 福利院收入走势（时间）'''
        _filter = self.___org_area_organization('福利院')
        _filter.inner_join_bill('PT_Financial_Book','user_info.id','user_id','book_info')\
            .inner_join_bill('PT_Financial_Account','book_info.id','book_id','account_info')\
            .inner_join_bill('PT_Financial_Account_Record','account_info.id','account_id','record_info')\
            .match(C("record_info.borrow_loan") == 'borrow')
        _filter = self._group_by_date(_filter,'$record_info.date','日')
        _filter.group({'x': '$new_date'},[{'y':self.ao.summation('$record_info.amount')}]).limit(12)
        print(_filter.filter_objects)
        res  = self.query(_filter,self.business_area_collection)
        return res
    #success

    def org_statistics_time_expenditure_quantity(self, condition, page, count):
        '''机构养老 统计 福利院支出走势（时间'''
        _filter = self.___org_area_organization('福利院')
        _filter.inner_join_bill('PT_Financial_Book','user_info.id','user_id','book_info')\
            .inner_join_bill('PT_Financial_Account','book_info.id','book_id','account_info')\
            .inner_join_bill('PT_Financial_Account_Record','account_info.id','account_id','record_info')\
            .match(C("record_info.borrow_loan") == 'loan')
        _filter = self._group_by_date(_filter,'$record_info.date','日')
        _filter.group({'x': '$new_date'},[{'y':self.ao.summation('$record_info.amount')}]).limit(12)
        res  = self.query(_filter,self.business_area_collection)
        return res
    # suucess

    def sep_statistics_service_provider_satisfaction_quantity(self, condition, page, count):
        '''服务商 统计 服务商满意度(服务商)'''
        _filter = self.___org_area_organization('服务商')
        _filter.unwind('user_info.qualification_info')\
            .inner_join('PT_Qualification_Type','user_info.qualification_info.qualification_type_id','id','qualification_type')\
            .match(C('qualification_type.name').like('满意度'))\
            .group({'x':'$user_info.name'},[{'y':self.ao.avg('$user_info.qualification_info.qualification_level')}]).limit(12)
        res = self.query(_filter,self.business_area_collection)
        return res
    #success
    #
    def sep_statistics_nature_satisfaction_quantity(self, condition, page, count):
        '''服务商 统计 服务商满意度(机构性质)'''
        _filter = self.___org_area_organization('服务商')
        _filter.unwind('user_info.qualification_info')\
            .inner_join('PT_Qualification_Type','user_info.qualification_info.qualification_type_id','id','qualification_type')\
            .match(C('qualification_type.name').like('满意度'))\
            .group({'x':'$user_info.organization_info.organization_nature'},[{'y':self.ao.avg('$user_info.qualification_info.qualification_level')}])\
            .limit(12)
        res = self.query(_filter,self.business_area_collection)
        if res:
            for result in res:
                result['y'] = round(float(result.get('y')),2)
        return res
    #success
    def eld_statistics_condition_service_quantity(self, condition, page, count):
        '''长者 统计 服务次数（病情）'''
        _filter = self.__eld_area_basic()
        _filter.inner_join('PT_Disease_Record','user_info.id','user_id','disease_record')\
            .inner_join('PT_Disease_Type','disease_record.disease_type_id','id','disease_type')\
            .inner_join_bill('PT_Service_Order','user_info.id','purchaser_id','order_info')\
            .inner_join_bill('PT_Service_Record','order_info.id','order_id','record_info')\
            .group({'x': '$disease_type.name'},[{'y':self.ao.summation(1)}]).limit(10)
        print(_filter.filter_objects)
        res = self.query(_filter,self.business_area_collection)
        return res
    #success
    def eld_statistics_condition_buy_money_quantity(self, condition, page, count):
        '''长者 统计 服务金额（病情）'''
        _filter = self.__eld_area_basic()
        _filter.inner_join('PT_Disease_Record','user_info.id','user_id','disease_record')\
            .inner_join('PT_Disease_Type','disease_record.disease_type_id','id','disease_type')\
            .inner_join_bill('PT_Service_Order','user_info.id','purchaser_id','order_info')\
            .inner_join_bill('PT_Service_Record','order_info.id','order_id','record_info')\
            .group({'x': '$disease_type.name'},[{'y':self.ao.summation('$record_info.valuation_amount')}]).limit(10)
        res = self.query(_filter,self.business_area_collection)
        return res
    # suucess

    def spe_statistics_time_service_personal_quantity(self, condition, page, count):
        '''服务人员 统计 服务人员走势'''
        _filter = self.__sep_stat_service_person()
        _filter = self._group_by_date(_filter,'$servicer_info.reg_date','日')
        _filter.group({'x':'$new_date'},[{'y':self.ao.summation(1)}])
        res = self.query(_filter,self.business_area_collection)
        if res:
            result = self.mega_sum(list(i.get('y') for i in res))
            for j in range(len(res)):
                res[j]['y'] = result[j]
            return res
        else:
            return []

    # def cop_statistics_donation_income_quantity(self, condition, page, count):
    #     '''慈善资金收入类型对比'''
        # _filter = self.__org_area()
        # _filter.inner_join_bill()
        #     .match_bill((C('borrow_loan') == borrowLoan.income.value) & (C('fund_type') == fundType.fund.value))\
        #     .group({'x': '$fund_type'}, [{'y': self.ao.summation('$fund_total')}])\
        #     .sort({'y': -1})
        # res = self.query(_filter, self.bus_area)
        # return res

    def cop_map_location(self, condition, page, count):
        '''综合 地图 星空图（服务事件）'''
        _filter = self.__sep_stat_service_person()
        _filter.inner_join_bill('PT_Service_Record','servicer_info.id','servicer_id','record_info')\
            .inner_join_bill('PT_Task','record_info.id','task_service_record_id','task_info')\
            .unwind('task_info.task_handler_travel')\
            .match((C('task_info.task_handler_travel.event') == '到达'))\
            .project({'_id':0,'x':'$task_info.task_handler_travel.lon','y':'$task_info.task_handler_travel.lat','z':'$task_info.task_name','id':'$task_info.id'})
        res = self.query(_filter,self.business_area_collection)
        result = [{
            'mapType':'scatter',
            'name':'星空图',
            'data':res,
        }]
        return result
    #success

    def cop_card_location(self, condition, page, count):
        '''综合 地图 当前任务卡片(服务人员)'''
        _filter = self.__sep_stat_service_person()
        _filter.inner_join_bill('PT_Service_Record','servicer_info.id','servicer_id','record_info')\
            .lookup_bill('PT_Service_Product','record_info.service_product_id','id','product_info')\
            .inner_join_bill('PT_Task','record_info.id','task_service_record_id','task_info')\
            .unwind('task_info.task_handler_travel')\
            .match((C('task_info.task_handler_travel.event') == '到达'))\
            .project({'_id':0,'y1':'$task_info.task_code','y2':'$product_info.name','y3':'$task_info.task_address','y4':'$record_info.start_date','x1':'$task_info.task_handler_travel.lon','x2':'$task_info.task_handler_travel.lat'})
        res = self.query(_filter,self.business_area_collection)
        res_list = self.___list_transform(res)
        return res_list
    #success

    def cop_hot_location_quantity(self, condition, page, count):
        '''综合 地图 星空图（服务事件）'''
        _filter = self.__sep_stat_service_person()
        _filter.inner_join_bill('PT_Service_Record','servicer_info.id','servicer_id','record_info')\
            .inner_join_bill('PT_Task','record_info.id','task_service_record_id','task_info')\
            .unwind('task_info.task_handler_travel')\
            .match((C('task_info.task_handler_travel.event') == '到达'))\
            .project({'_id':0,'x':'$task_info.task_handler_travel.lon','y':'$task_info.task_handler_travel.lat'})
        res = self.query(_filter,self.business_area_collection)
        result = [{
             'mapType':'scatter',
            'name':'星空图',
            'data':res,
        }]
        return result 
    #success

    def org_detail_origin_quantity(self, condition, page, count):
        '''机构养老 明细 长者数量（来源地）'''
        _filter = self.___current_user(condition)
        _filter.match((C('personnel_type') == UserType.Organizational) & (C('organization_info.personnel_category') == '福利院'))\
            .inner_join_bill('PT_Hotel_Zone','id','organization_id','hotel_zone')\
            .inner_join_bill('PT_Bed','hotel_zone.id','area_id','bed_info')\
            .inner_join_bill("PT_User",'bed_info.residents_id','id','elder_info')\
            .group({'x':'$elder_info.town'},[{'y':self.ao.summation(1)}])
        res = self.query(_filter,'PT_User')
        return res
    # success

    def cop_statistics_donation_income_quantity(self, condition, page, count):
        '''综合 统计 慈善收入金额'''
        _filter = self.__org_area()
        _filter.inner_join_bill('PT_Financial_Book','user_info.id','user_id','book_info')\
            .inner_join_bill('PT_Financial_Account','book_info.id','book_id','account_info')\
            .inner_join_bill('PT_Financial_Account_Record','account_info.id','account_id','account_record_info')\
            .inner_join_bill('PT_Financial_Account_Record_Directional','account_record_info.id','account_record_id','account_record_dorection_info')\
            .match((C('pool_info.fund_use_direction').like('慈善')) & (C('account_record_info.borrow_loan')  == 'borrow'))\
            .gorup({'x'})
            
    def org_detail_star_personnel_quantity(self, condition, page, count):
        '''机构养老 明细 工作人员数量（星级）''' 
        _filter = self.___current_user(condition)
        _filter.match((C('personnel_type') == UserType.Organizational) & (C('organization_info.personnel_category') == '福利院'))\
            .inner_join_bill('PT_User_Relationship','id','main_relation_people','relationship')\
            .inner_join_bill('PT_User_Relationship_Type','relationship.relationship_type_id','id','relation_type')\
            .match((C('relation_type.name') == '雇佣'))\
            .inner_join_bill('PT_User','relationship.subordinate_relation_people','id','servicer_info')\
            .unwind('servicer_info.qualification_info')\
            .inner_join_bill('PT_Qualification_Type','servicer_info.qualification_info.qualification_type_id','id','qualification_type')\
            .match((C('qualification_type.name') == '服务评级'))\
            .group({'x':'$servicer_info.qualification_info.name'},[{'y':self.ao.summation(1)}])
        print(_filter.filter_objects)
        res = self.query(_filter,'PT_User')
        return res
    #success

    def cop_statistics_service_provider_total_quantity(self, condition, page, count):
        '''综合统计 服务商总数'''
        _filter1 = self.___org_area_organization('服务商')
        _filter1.group({'x': '$user_info.id'})\
            .count('y')
        res1 = self.query(_filter1, self.business_area_collection)
        '''服务人员总数'''
        _filter2 = self.__sep_stat_service_person()
        _filter2.group({'x': '$servicer_info.id'})\
               .count('y')
        res2 = self.query(_filter2, self.business_area_collection)
        '''长者总数'''
        _filter3 = self.__eld_area_basic()
        _filter3.group({'x': '$user_info.id'}).count('y')
        res3 = self.query(_filter3, self.business_area_collection)
        res = res1 + res2 + res3
        return res
    
    def org_detail_time_line_up_quantity(self, condition, page, count):
        '''机构养老-明细-预约入住人数走势'''
        _filter = self.___current_user(condition)

    




        

